package org.example.Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:阻塞队列
 * User:Lenovo
 * Date:2022-04-09
 * Time:14:40
 */
class MyBolckingQueue{
    private int[] data = new int[1000];
    private int size = 0;//有效元素个数
    private int head = 0;//队首下标
    private int tail = 0;//队尾下标
    private Object locker = new Object();//专门的锁对象

    //入队列
    public void put(int val){
        synchronized (locker){
            if(size == data.length){
                //阻塞条件,就是队列满了
                //队列满了,暂时先直接返回
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //把新的元素放到tail下标
            data[tail] = val;
            tail++;
            size++;
            //如果入队列成功,则队列非空,于是就唤醒take中的阻塞等待
            locker.notify();
            //处理tail到达数组末尾的情况
            if(tail >= data.length){
                tail = 0;
            }
        }
    }
    //出队列
    public Integer take(){
        synchronized (locker){
            if(size == 0){
                //队列为空,就返回一个非法值
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //取出head下标的元素
            int ret = data[head];
            head++;
            if(head >= data.length){
                head = 0;
            }
            size--;
            //take成功之后,就唤醒put中的等待
            locker.notify();
            return ret;
        }
    }
}
public class Demo16 {
    public static void main(String[] args) {
        MyBolckingQueue myBolckingQueue = new MyBolckingQueue();

    }
}
